package com.gy.boot.common.exception;

import com.gy.boot.common.util.R;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.NoHandlerFoundException;

import java.io.IOException;

/**
 * TODO 全局异常处理器
 * @author geYang 2018-05-11
 */
@RestControllerAdvice
public class SysExceptionHandler {
    private Logger logger = LoggerFactory.getLogger(getClass());
    
    /**
     * 处理自定义异常
     */
    @ExceptionHandler(SysException.class)
    public R handleSysException(SysException e) {
        return R.err(e);
    }
    
    @ExceptionHandler(IOException.class)
    public R handlerIOException(Exception e) {
    	logger.error(e.getMessage(), e);
    	return R.err("流文件异常").set("errMsg", e.getMessage());
    }

    @ExceptionHandler(NoHandlerFoundException.class)
    public R handlerNoFoundException(Exception e) {
        logger.error(e.getMessage(), e);
        return R.err(404, "请求地址不存在").set("errMsg", e.getMessage());
    }

    @ExceptionHandler(DuplicateKeyException.class)
    public R handleDuplicateKeyException(DuplicateKeyException e) {
        logger.error(e.getMessage(), e);
        return R.err("该记录已存在").set("errMsg", e.getMessage());
    }

    @ExceptionHandler(Exception.class)
    public R handleException(Exception e) {
        logger.error(e.getMessage(), e);
        return R.err("未知异常,请联系管理员").set("errMsg", e.getMessage());
    }
    

}
